package api

import (
	"net/http"

	"example.com/example/dao"
	"example.com/example/model"

	"github.com/gin-gonic/gin"
	"github.com/guregu/null"
	"github.com/julienschmidt/httprouter"
)

var (
	_ = null.Bool{}
)

func configGoodsRouter(router *httprouter.Router) {
	router.GET("/goods", GetAllGoods)
	router.POST("/goods", AddGoods)
	router.GET("/goods/:argId", GetGoods)
	router.PUT("/goods/:argId", UpdateGoods)
	router.DELETE("/goods/:argId", DeleteGoods)
}

func configGinGoodsRouter(router gin.IRoutes) {
	router.GET("/goods", ConverHttprouterToGin(GetAllGoods))
	router.POST("/goods", ConverHttprouterToGin(AddGoods))
	router.GET("/goods/:argId", ConverHttprouterToGin(GetGoods))
	router.PUT("/goods/:argId", ConverHttprouterToGin(UpdateGoods))
	router.DELETE("/goods/:argId", ConverHttprouterToGin(DeleteGoods))
}

// GetAllGoods is a function to get a slice of record(s) from goods table in the custom_process database
// @Summary Get list of Goods
// @Tags Goods
// @Description GetAllGoods is a handler to get a slice of record(s) from goods table in the custom_process database
// @Accept  json
// @Produce  json
// @Param   page     query    int     false        "page requested (defaults to 0)"
// @Param   pagesize query    int     false        "number of records in a page  (defaults to 20)"
// @Param   order    query    string  false        "db sort order column"
// @Success 200 {object} api.PagedResults{data=[]model.Goods}
// @Failure 400 {object} api.HTTPError
// @Failure 404 {object} api.HTTPError
// @Router /goods [get]
// http "http://localhost:8080/goods?page=0&pagesize=20" X-Api-User:user123
func GetAllGoods(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
	ctx := initializeContext(r)
	page, err := readInt(r, "page", 0)
	if err != nil || page < 0 {
		returnError(ctx, w, r, dao.ErrBadParams)
		return
	}

	pagesize, err := readInt(r, "pagesize", 20)
	if err != nil || pagesize <= 0 {
		returnError(ctx, w, r, dao.ErrBadParams)
		return
	}

	order := r.FormValue("order")

	if err := ValidateRequest(ctx, r, "goods", model.RetrieveMany); err != nil {
		returnError(ctx, w, r, err)
		return
	}

	records, totalRows, err := dao.GetAllGoods(ctx, page, pagesize, order)
	if err != nil {
		returnError(ctx, w, r, err)
		return
	}

	result := &PagedResults{Page: page, PageSize: pagesize, Data: records, TotalRecords: totalRows}
	writeJSON(ctx, w, result)
}

// GetGoods is a function to get a single record from the goods table in the custom_process database
// @Summary Get record from table Goods by  argId
// @Tags Goods
// @ID argId
// @Description GetGoods is a function to get a single record from the goods table in the custom_process database
// @Accept  json
// @Produce  json
// @Param  argId path int64 true "id"
// @Success 200 {object} model.Goods
// @Failure 400 {object} api.HTTPError
// @Failure 404 {object} api.HTTPError "ErrNotFound, db record for id not found - returns NotFound HTTP 404 not found error"
// @Router /goods/{argId} [get]
// http "http://localhost:8080/goods/1" X-Api-User:user123
func GetGoods(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
	ctx := initializeContext(r)

	argId, err := parseUint64(ps, "argId")
	if err != nil {
		returnError(ctx, w, r, err)
		return
	}

	if err := ValidateRequest(ctx, r, "goods", model.RetrieveOne); err != nil {
		returnError(ctx, w, r, err)
		return
	}

	record, err := dao.GetGoods(ctx, argId)
	if err != nil {
		returnError(ctx, w, r, err)
		return
	}

	writeJSON(ctx, w, record)
}

// AddGoods add to add a single record to goods table in the custom_process database
// @Summary Add an record to goods table
// @Description add to add a single record to goods table in the custom_process database
// @Tags Goods
// @Accept  json
// @Produce  json
// @Param Goods body model.Goods true "Add Goods"
// @Success 200 {object} model.Goods
// @Failure 400 {object} api.HTTPError
// @Failure 404 {object} api.HTTPError
// @Router /goods [post]
// echo '{"id": 70,"name": "jvGZshMXGrXxKxOclCrgCVHkO","create_time": "2180-11-15T09:10:16.765008018+08:00","update_time": "2095-03-09T18:23:59.906139174+08:00"}' | http POST "http://localhost:8080/goods" X-Api-User:user123
func AddGoods(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
	ctx := initializeContext(r)
	goods := &model.Goods{}

	if err := readJSON(r, goods); err != nil {
		returnError(ctx, w, r, dao.ErrBadParams)
		return
	}

	if err := goods.BeforeSave(); err != nil {
		returnError(ctx, w, r, dao.ErrBadParams)
	}

	goods.Prepare()

	if err := goods.Validate(model.Create); err != nil {
		returnError(ctx, w, r, dao.ErrBadParams)
		return
	}

	if err := ValidateRequest(ctx, r, "goods", model.Create); err != nil {
		returnError(ctx, w, r, err)
		return
	}

	var err error
	goods, _, err = dao.AddGoods(ctx, goods)
	if err != nil {
		returnError(ctx, w, r, err)
		return
	}

	writeJSON(ctx, w, goods)
}

// UpdateGoods Update a single record from goods table in the custom_process database
// @Summary Update an record in table goods
// @Description Update a single record from goods table in the custom_process database
// @Tags Goods
// @Accept  json
// @Produce  json
// @Param  argId path int64 true "id"
// @Param  Goods body model.Goods true "Update Goods record"
// @Success 200 {object} model.Goods
// @Failure 400 {object} api.HTTPError
// @Failure 404 {object} api.HTTPError
// @Router /goods/{argId} [put]
// echo '{"id": 70,"name": "jvGZshMXGrXxKxOclCrgCVHkO","create_time": "2180-11-15T09:10:16.765008018+08:00","update_time": "2095-03-09T18:23:59.906139174+08:00"}' | http PUT "http://localhost:8080/goods/1"  X-Api-User:user123
func UpdateGoods(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
	ctx := initializeContext(r)

	argId, err := parseUint64(ps, "argId")
	if err != nil {
		returnError(ctx, w, r, err)
		return
	}

	goods := &model.Goods{}
	if err := readJSON(r, goods); err != nil {
		returnError(ctx, w, r, dao.ErrBadParams)
		return
	}

	if err := goods.BeforeSave(); err != nil {
		returnError(ctx, w, r, dao.ErrBadParams)
	}

	goods.Prepare()

	if err := goods.Validate(model.Update); err != nil {
		returnError(ctx, w, r, dao.ErrBadParams)
		return
	}

	if err := ValidateRequest(ctx, r, "goods", model.Update); err != nil {
		returnError(ctx, w, r, err)
		return
	}

	goods, _, err = dao.UpdateGoods(ctx,
		argId,
		goods)
	if err != nil {
		returnError(ctx, w, r, err)
		return
	}

	writeJSON(ctx, w, goods)
}

// DeleteGoods Delete a single record from goods table in the custom_process database
// @Summary Delete a record from goods
// @Description Delete a single record from goods table in the custom_process database
// @Tags Goods
// @Accept  json
// @Produce  json
// @Param  argId path int64 true "id"
// @Success 204 {object} model.Goods
// @Failure 400 {object} api.HTTPError
// @Failure 500 {object} api.HTTPError
// @Router /goods/{argId} [delete]
// http DELETE "http://localhost:8080/goods/1" X-Api-User:user123
func DeleteGoods(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
	ctx := initializeContext(r)

	argId, err := parseUint64(ps, "argId")
	if err != nil {
		returnError(ctx, w, r, err)
		return
	}

	if err := ValidateRequest(ctx, r, "goods", model.Delete); err != nil {
		returnError(ctx, w, r, err)
		return
	}

	rowsAffected, err := dao.DeleteGoods(ctx, argId)
	if err != nil {
		returnError(ctx, w, r, err)
		return
	}

	writeRowsAffected(w, rowsAffected)
}
